package com.tim.app.ui.fragment.selceted;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.application.library.base.BaseFragment;
import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.HorizontalDividerItemDecoration;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.application.library.widget.refresh.PtrClassicFrameLayout;
import com.application.library.widget.refresh.PtrDefaultHandler;
import com.application.library.widget.refresh.PtrFrameLayout;
import com.application.library.widget.refresh.PtrHandler;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.cache.CacheMode;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MsgService;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.db.dao.DaoFactory;
import com.tim.app.server.api.API_App;
import com.tim.app.server.entry.SelectInfo;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.HomeSelectedResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.activity.MainActivity;
import com.tim.app.ui.activity.SearchActivity;
import com.tim.app.ui.activity.message.MessageActivity;
import com.tim.app.ui.activity.selected.AskQuestionActivity;
import com.tim.app.ui.adapter.selceted.SelectedInfoItemAdapter;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

import java.util.ArrayList;
import java.util.List;

/**
 * 问答页面
 */
public class SelectedFragment extends BaseFragment implements View.OnClickListener, PtrHandler, LoadMoreHandler, BaseRecyclerAdapter.OnItemClickListener {

    public static final String TAG = "SelectedFragment";
    private int pageNumber = 1;
    private View rootView;
    private PtrClassicFrameLayout refresh_layout;
    private LoadMoreRecycleViewContainer load_more;
    private WrapRecyclerView wrv_selected;
    private EmptyLayout emptyLayout;
    private EditText etSearch;
    private ImageView ivNoticeIcon;
    private SelectedInfoItemAdapter adapter;
    private List<SelectInfo> infoList;

    private View llActionContainer;
    private RelativeLayout rlAskQuestion;
    private RelativeLayout rlAnswer;

    LinearLayoutManager layoutManager;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == rootView) {
            rootView = inflater.inflate(R.layout.fragment_tab_selected, container, false);

            refresh_layout = (PtrClassicFrameLayout) rootView.findViewById(R.id.refresh_layout);

            load_more = (LoadMoreRecycleViewContainer) rootView.findViewById(R.id.load_more);
            wrv_selected = (WrapRecyclerView) rootView.findViewById(R.id.wrv_selected);
            wrv_selected.setOverScrollMode(View.OVER_SCROLL_NEVER);

            llActionContainer = rootView.findViewById(R.id.llActionContainer);

            etSearch = (EditText) rootView.findViewById(R.id.etSearch);
            ivNoticeIcon = (ImageView) rootView.findViewById(R.id.ivNoticeIcon);
            rlAskQuestion = (RelativeLayout) rootView.findViewById(R.id.rlAskQuestion);
            rlAnswer = (RelativeLayout) rootView.findViewById(R.id.rlAnswer);

            rlAnswer.setOnClickListener(this);
            rlAskQuestion.setOnClickListener(this);
            ivNoticeIcon.setOnClickListener(this);
            etSearch.setOnClickListener(this);

            refresh_layout.disableWhenHorizontalMove(true);
            refresh_layout.setPtrHandler(this);
            load_more.useDefaultFooter(View.GONE);
            load_more.setAutoLoadMore(true);
            load_more.setLoadMoreHandler(this);

            emptyLayout = new EmptyLayout(getActivity(), refresh_layout);
            emptyLayout.showLoading();
            emptyLayout.setEmptyButtonClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    emptyLayout.showLoading();
                    pageNumber = 1;
                    API_App.ins().getSelectedData(TAG, pageNumber, CacheMode.REQUEST_FAILED_READ_CACHE, initCallback);
                }
            });

            layoutManager = new LinearLayoutManager(getActivity());
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            wrv_selected.setLayoutManager(layoutManager);
            wrv_selected.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(getResources().getColor(R.color.view_background_color)).size((int) getResources().getDimension(R.dimen.splitLineHeight)).build());
            infoList = new ArrayList<>();
            adapter = new SelectedInfoItemAdapter(getActivity(), infoList);
            wrv_selected.setAdapter(adapter);
            adapter.setOnItemClickListener(this);

            API_App.ins().getSelectedData(TAG, pageNumber, CacheMode.REQUEST_FAILED_READ_CACHE, initCallback);
        } else {
            if (refresh_layout != null) {
                refresh_layout.refreshComplete();
            }
        }
        EventManager.ins().registListener(EventTag.DO_REFRESH_SELECTED, eventListener);
        EventManager.ins().registListener(EventTag.ON_MESSAGE_STATED_CHANGED, eventListener);
        EventManager.ins().registListener(EventTag.ACCOUNT_LOGIN, eventListener);
        EventManager.ins().registListener(EventTag.ACCOUNT_LOGOUT, eventListener);
        showUnreadMesageView();

        ((MainActivity) getActivity()).registerMyOnTouchListener(mTouchListener);
        return rootView;
    }

    //手指按下的点为(x1, y1)手指离开屏幕的点为(x2, y2)
    float y1 = 0;
    float y2 = 0;

    private MainActivity.MyOnTouchListener mTouchListener = new MainActivity.MyOnTouchListener() {

        @Override
        public boolean onTouch(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                //当手指按下的时候
                y1 = event.getY();
            } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                //当手指离开的时候
                y2 = event.getY();
                if (y1 - y2 > 15) {
                    llActionContainer.setVisibility(View.GONE);
                } else if (y2 - y1 > 15) {
                    llActionContainer.setVisibility(View.VISIBLE);
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {

            }
            return false;
        }
    };

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.DO_REFRESH_SELECTED:
                    wrv_selected.scrollToPosition(0);
                    refresh_layout.autoRefresh();
                    break;
                case EventTag.ON_MESSAGE_STATED_CHANGED:
                    boolean isShow = (boolean) dataobj;
                    ivNoticeIcon.setSelected(isShow);
                    break;
                case EventTag.ACCOUNT_LOGIN:
                    showUnreadMesageView();
                    break;
                case EventTag.ACCOUNT_LOGOUT:
                    ivNoticeIcon.setSelected(false);
                    break;
            }
        }
    };

    @Override
    public void onItemClick(View view, int position, long id) {
        if (null == infoList || position > infoList.size() - 1)
            return;
        SelectInfo info = infoList.get(position);
        ViewGT.gotoDetailActivity(getActivity(), info);
    }

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            refresh_layout.refreshComplete();
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                HomeSelectedResult result = new Gson().fromJson(resultValue, HomeSelectedResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getHashmap() && null != result.getRes().getHashmap().getPageDiscover()) {
                    pageNumber = result.getRes().getHashmap().getPageNum();
                    if (null != result.getRes().getHashmap().getPageTopic() && null != result.getRes().getHashmap().getPageTopic().getResult()) {
                        SelectInfo subjectInfo = new SelectInfo();
                        subjectInfo.setDiscoverType(AppKey.TYPE_TOPIC);
                        subjectInfo.setSubjectList(result.getRes().getHashmap().getPageTopic().getResult());
                        infoList.add(0, subjectInfo);
                    }
                    infoList.addAll(0, result.getRes().getHashmap().getPageDiscover());
                }
                adapter.notifyDataSetChanged();
            } else {
                ToastUtil.showToast(errMsg);
            }
            return true;
        }
    };

    StringResponseCallback initCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            refresh_layout.refreshComplete();
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                if (infoList != null) {
                    infoList.clear();
                }
                HomeSelectedResult result = new Gson().fromJson(resultValue, HomeSelectedResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getHashmap() && null != result.getRes().getHashmap().getPageDiscover()) {
                    infoList.addAll(result.getRes().getHashmap().getPageDiscover());
                    pageNumber = result.getRes().getHashmap().getPageNum();
                    if (null != result.getRes().getHashmap().getPageTopic() && null != result.getRes().getHashmap().getPageTopic().getResult()) {
                        SelectInfo subjectInfo = new SelectInfo();
                        subjectInfo.setDiscoverType(AppKey.TYPE_TOPIC);
                        subjectInfo.setSubjectList(result.getRes().getHashmap().getPageTopic().getResult());
                        infoList.add(subjectInfo);
                    }
                }
                adapter.notifyDataSetChanged();

                if (infoList == null || infoList.size() == 0) {
                    emptyLayout.showEmpty();
                } else {
                    emptyLayout.showContent();
                }
            } else {
                emptyLayout.showEmptyOrError(errCode);
                ToastUtil.showToast(errMsg);
            }
            return true;
        }
    };


    StringResponseCallback moreCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                HomeSelectedResult result = new Gson().fromJson(resultValue, HomeSelectedResult.class);
                if (null != result && null != result.getRes() && null != result.getRes().getHashmap() && null != result.getRes().getHashmap().getPageDiscover()) {
                    if (null != result.getRes().getHashmap().getPageDiscover() && result.getRes().getHashmap().getPageDiscover().size() > 0) {
                        pageNumber = result.getRes().getHashmap().getPageNum();
                        infoList.addAll(result.getRes().getHashmap().getPageDiscover());
                        if (null != result.getRes().getHashmap().getPageTopic() && null != result.getRes().getHashmap().getPageTopic().getResult()) {
                            SelectInfo subjectInfo = new SelectInfo();
                            subjectInfo.setDiscoverType(AppKey.TYPE_TOPIC);
                            subjectInfo.setSubjectList(result.getRes().getHashmap().getPageTopic().getResult());
                            infoList.add(subjectInfo);
                        }
                        load_more.loadMoreFinish(false, true);
                        adapter.notifyDataSetChanged();
                    }
                }
            } else {
                ToastUtil.showToast(errMsg);
            }
            return true;
        }
    };

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != rootView && null != rootView.getParent()) {
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(TAG);
        EventManager.ins().removeListener(EventTag.DO_REFRESH_SELECTED, eventListener);
        EventManager.ins().removeListener(EventTag.ON_MESSAGE_STATED_CHANGED, eventListener);
        EventManager.ins().removeListener(EventTag.ACCOUNT_LOGIN, eventListener);
        EventManager.ins().removeListener(EventTag.ACCOUNT_LOGOUT, eventListener);
    }

    /**
     * 消息的view
     */
    private void showUnreadMesageView() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final int unReadMessageTotalCount = NIMClient.getService(MsgService.class).getTotalUnreadCount();
                final int unReadNoticeCount = DaoFactory.getNoticeDao().getUnReadMessageCount();
                if (unReadMessageTotalCount > 0 || unReadNoticeCount > 0 || UserManager.ins().getUnreadOfficialMessageCount() > 0) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ivNoticeIcon.setSelected(true);
                        }
                    });
                }
            }
        }).start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivNoticeIcon:
                if (UserManager.ins().isLogin()) {
                    MessageActivity.start(getActivity());
                } else {
                    ViewGT.gotoLoginActivity(getActivity());
                }
                break;
            case R.id.etSearch:
                SearchActivity.start(getContext(), SearchActivity.SEARCH_ALL, "");
                break;
            case R.id.rlAnswer:
                EventManager.ins().sendEvent(EventTag.GOTO_ANSWER, 0, 0, null);
                break;
            case R.id.rlAskQuestion:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(getContext());
                    return;
                }
                Intent intentAsk = new Intent(getContext(), AskQuestionActivity.class);
                intentAsk.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                getContext().startActivity(intentAsk);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        int firstCompletelyVisibleItem = layoutManager.findFirstCompletelyVisibleItemPosition();
        if(firstCompletelyVisibleItem ==0){
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, wrv_selected, header);
        }else{
            return false;
        }
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        API_App.ins().getSelectedData(TAG, pageNumber, CacheMode.REQUEST_FAILED_READ_CACHE, refreshCallback);
    }


    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        API_App.ins().getSelectedData(TAG, pageNumber, CacheMode.REQUEST_FAILED_READ_CACHE, moreCallback);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


}
